package com.mkh.st.common.core.serializer;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Author: xhx
 * Date: 2021/10/26 5:10 下午
 * FileName: ListJsonStringDeserializer
 * Description:
 */
public class String2ListDeserializer extends JsonDeserializer<String> {

	private final static Logger logger = LoggerFactory.getLogger(String2ListDeserializer.class);

	@Override
	public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ArrayNode treeNode = jp.readValueAsTree();
		logger.debug("使用自定义解析器解析字段:{}:时间:{}",jp.getCurrentName(),jp.getText());
		Iterator<JsonNode> elements = treeNode.elements();
		List<String> result = new ArrayList<>();
		while (elements.hasNext()) {
			try {
				result.add(elements.next().asText());
			} catch (IllegalArgumentException e) {
				continue;
			}
		}
		if (result.isEmpty()){
			return null;
		}else {
			return Joiner.on(",").join(result);
		}

	}
}
